//
//  WmcHomeVM+Photo.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/7/26.
//

import UIKit
import YPBedrock

extension WmcHomeVM {
    /// 二维码图片元组(原始二维码和验证二维码)
    typealias QRCodeImageResult = WmcWatermarkUtil.QRCodeImageResult
    
    /// 合成图片
    func fotoMix(_ image: UIImage, watermarkContentView: WmcWatermarkContentView, qrcodeView: WmcQRCodeVerifyView? = nil, completeBlock: YPBlock.Empty? = nil) {
        guard let contentWatermarkModel = watermarkContentView.watermarkModel?.copyModel() else { return }
        // 显示官方水印
        if contentWatermarkModel.templateId != 0, // 不是无水印
           !WmcPreferenceSettingsManager.shared.cameraSetting.hiddenOfficialMark { // 没隐藏官水印
            watermarkContentView.showOfficialWatermark()
        }
        guard let watermarkImage = watermarkContentView.yp.screenshot() else { return }
        // 隐藏官方水印
        watermarkContentView.hideOfficialWatermark()
        // 生成二维码信息
        let qrImageResult = WmcWatermarkUtil.makeQRImageResult(with: contentWatermarkModel, qrcodeView: qrcodeView)
        // 异步处理图片
        transactionQueue.async { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.asyncFotoMix(image, watermarkImage: watermarkImage, watermarkModel: contentWatermarkModel, qrImageResult: qrImageResult)
            completeBlock?()
        }
    }
    
    
    /// 异步生成图片
    func asyncFotoMix(_ photo: UIImage, watermarkImage: UIImage, watermarkModel: WmcWatermarkDetailModel, qrImageResult: QRCodeImageResult) {
        // 询问外部代理支持的方向
        var defaultOrientation: [UIDeviceOrientation] = defaultOrientation
        if let _defaultOrientation = homeDelegate?.cameraRotatingOrientation(.current,
                                                                             functionMode: functionMode,
                                                                             videoRecordState: videoRecordState,
                                                                             defaultOrientation: defaultOrientation)
        {
            defaultOrientation = _defaultOrientation
        }
        let orientation = WmcMotionManager.shared.orientation.value
        var standardImage: UIImage? = photo
//        WmcAlbumManager.saveMyAlbumCollection(image: photo)
        if defaultOrientation.contains(orientation) {
            // 旋转原图
            var angle: CGFloat = 0
            switch WmcMotionManager.shared.orientation.value {
            case .portrait:
                angle = 0 // 直立
            case .landscapeRight:
                angle = 90 // 右
            case .portraitUpsideDown:
                angle = 180 // 反向
            case .landscapeLeft:
                angle = 270 // 左
            default: break
            }
            standardImage = photo.yp.setRotate(angle: angle)
        }
        guard let standardImage = standardImage else { return }
        // 合成照片
        let drawWatermarkImage = WmcWatermarkUtil.makeImage(standardImage: standardImage, watermarkImage: watermarkImage, qrVerImage: qrImageResult.qrVerImage)
        // 生成带水印的标准图片
        guard let watermarkPhoto = drawWatermarkImage else { return }
        // 主线程回调
        YPGCD.Main { [weak self] in
            guard let weakSelf = self else { return }
            // 锁拍摄数据
            watermarkModel.saveStaticInformation()
            // 标记定位
            watermarkModel.createLocationInfo()
            // 图片处理完成回调
            weakSelf.photoDisposeFinishRelay.accept((watermarkPhoto, standardImage, watermarkModel, qrImageResult.qrImage))
        }
    }

    /// 保存图片
    func saveImage(watermarkPhoto: UIImage, standardPhoto: UIImage, watermarkModel: WmcWatermarkDetailModel, qrcodePhoto: UIImage?) {
        // 异步处理图片
        transactionQueue.async { [weak self] in
            guard let weakSelf = self else { return }
            // 保存和上传图片
            weakSelf.saveAndUpload(watermarkPhoto: watermarkPhoto, standardPhoto: standardPhoto, watermarkModel: watermarkModel, qrcodePhoto: qrcodePhoto)
            // 存入系统相册
            WmcAlbumManager.saveMyAlbumCollection(image: watermarkPhoto)
            // 是否保存原图
            if WmcPreferenceSettingsManager.shared.cameraSetting.saveNoneWatermarkImage {
                WmcAlbumManager.saveMyAlbumCollection(image: standardPhoto)
            }
        }
    }

    /// 保存和上传图片
    func saveAndUpload(watermarkPhoto: UIImage,
                       standardPhoto: UIImage,
                       watermarkModel: WmcWatermarkDetailModel,
                       qrcodePhoto: UIImage?)
    {
        // 生成水印信息
        let watermarkInfoDic: [String: Any] = watermarkModel.toJSON() ?? [:]
        let watermarkInfo = WmcWatermarkDataTool.createWatermark(watermarkInfoDic, addressModel: watermarkModel.staticData.drawStaticAddress, addressPrefix: watermarkModel.staticData.staticAddressPrefix)
        let noWatermarkInfo = WmcWatermarkDataTool.createNoneWatermark(addressModel: watermarkModel.staticData.drawStaticAddress, addressPrefix: watermarkModel.staticData.staticAddressPrefix)
        let noWatermarkModel = watermarkModel.copyModel()
        noWatermarkModel?.wmId = 0

        // 提交统计数据
        let watermarkType = watermarkModel.wmId.yp.string

        // 获取当前活动id
        var activity: YPWmcManager.ActivityType?
        let activityList = YPWmcManager.shared.delegate.activityDelegate?.openActivityType(.current)
        if activityList?.contains(.yp_giveIntegral) == true {
            activity = .yp_giveIntegral
        }
        WmcPhotoAPI.submitWatermarkInfo(watermarkType: watermarkType, type: 1, watermarkInfo: watermarkInfo.json, activity: activity?.info.activityValue, success: { [weak self] response in
            guard let weakSelf = self else { return }
            // 送积分业务线打卡天数
            if let dic = response.data as? [String: Any],
               let punchCardDayNum = dic["take_num"] as? Int
            {
                // 更新资格,再走一遍资格
                weakSelf.yupao_integral()
                // 回调
                weakSelf.business_punchCardDayNumRelay.accept(punchCardDayNum)
            }
        })
        
        // 询问是否上传
        var isUpload = true
        if let _isUpload = YPWmcManager.shared.delegate.infoDelegate?.photoIsUploadCloudAlbum(.current, photoResult: (watermarkPhoto,standardPhoto, watermarkModel, qrcodePhoto)) {
            isUpload = _isUpload
        }
        // 存储水印照片
        WmcLocalMediaAlbumDBManager.insertImage(.init(uiImage: watermarkPhoto),
                                                watermarkJson: watermarkInfo.json)
        { [weak self] mediaType, previewImagePath, previewImageRelativePath, mediaInfoModel in
            guard let weakSelf = self else { return }

            weakSelf.isLoginWithNewUser { isLogin in
                if isLogin && isUpload {
                    weakSelf.uploadImage(imagePath: mediaInfoModel.relativePath,
                                         watermarkModel: watermarkModel,
                                         watermarkInfo: watermarkInfo.dict,
                                         previewImagePath: previewImageRelativePath)
                    
                }
            }
            weakSelf.syncLocalAlbumList() // 同步下数据库
        }
        // 保存原图
        save(standardPhoto: standardPhoto, noWatermarkModel: noWatermarkModel, noWatermarkInfo: noWatermarkInfo, isUpload: isUpload)
        
    }
    
    /// 保存无水印原图到本地相册,并检测上传
    func save(standardPhoto: UIImage, noWatermarkModel: WmcWatermarkDetailModel?, noWatermarkInfo: (dict: [String: Any], json: String), isUpload: Bool) {
        // 是否保存原图
        guard let noWatermarkModel = noWatermarkModel,
              WmcCameraSettingVM.checkUseCell(type: .saveNoneWatermarkImage), // 有这个cell
              WmcPreferenceSettingsManager.shared.cameraSetting.saveNoneWatermarkImage // 设置-保存无水印
        else { return }
        WmcLocalMediaAlbumDBManager.insertImage(.init(uiImage: standardPhoto), watermarkJson: noWatermarkInfo.json) {
            [weak self]
            originMediaType, // 媒体类型
                originPreviewImagePath, // 预览图完整路径
                originPreviewImageRelativePath, // 预览图相对路径
                originMediaInfoModel // 媒体对象
            in
            guard let self = self else { return }
            self.syncLocalAlbumList() // 同步下数据库
            // 是否上传
            if !isUpload { return }
            var isUseUpload = false
            if WmcCameraSettingVM.checkUseCell(type: .uploadNoneWatermarkImage), // 有这个Cell
               WmcPreferenceSettingsManager.shared.cameraSetting.uploadNoneWatermarkImage { // 设置-上传无水印
                isUseUpload = true
            }
            if !isUseUpload { return }
            self.isLoginWithNewUser { isLogin in
                if !isLogin { return }
                self.uploadImage(imagePath: originMediaInfoModel.relativePath,
                                 watermarkModel: noWatermarkModel,
                                 watermarkInfo: noWatermarkInfo.dict,
                                 previewImagePath: originPreviewImageRelativePath,
                                 standardPhoto: standardPhoto)
            }
        }
    }

    /// 上传图片
    func uploadImage(imagePath: String,
                     watermarkModel: WmcWatermarkDetailModel,
                     watermarkInfo: [String: Any],
                     previewImagePath: String,
                     standardPhoto: UIImage? = nil)
    {
        var date = Date()

        if let networkDate = WmcDateManager.shared.networkDate.value {
            let timeInterval = networkDate.timeIntervalSince1970 - 8 * 60 * 60
            date = Date(timeIntervalSince1970: timeInterval)
        }

        // 调用上传
        let uploadParams = WmcMediaUploadResourceParameterModel()
        uploadParams.appId = 101 // 锁死水印相机appid
        uploadParams.entryId = 1
        uploadParams.type = 0
        uploadParams.format = "png"
        uploadParams.wmcInfo = watermarkInfo
        if let uid = WmcLoginManager.shared.yupaoAccountModel?.userId {
            uploadParams.uid = Int(uid)
        }
        uploadParams.wmId = watermarkModel.wmId
        uploadParams.takeTime = date.yp.string(.ymd_hms_iso8601, identifier: .asia(.Shanghai))
        uploadParams.previewImagePath = previewImagePath

        if let poi = watermarkModel.staticData.drawStaticAddress?.poi,
           let addressPrefix = watermarkModel.staticData.drawStaticAddress?.addressPrefix
        {
            uploadParams.city = poi.city
            if let poiName = poi.name {
                uploadParams.address = "\(addressPrefix)\(poiName)"
            }
        }

        WmcUploadQueueManager.appendUploadTask(path: imagePath, model: uploadParams)
    }
    
    // MARK: Private
    
    
}
